var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Goods = require('../models/goods');

//连接mongodb数据库
mongoose.connect("mongodb://dumall:123@192.168.3.97:27017/dumall");

//连接成功
mongoose.connection.on("connected",function () {
  console.log("MongoDB Connected success")
});

//连接失败
mongoose.connection.on("error",function () {
  console.log("MongoDB Connected fail")
});

//断开连接
mongoose.connection.on("disconnected",function () {
  console.log("MongoDB Connected disconnected")
});

router.get("/",function (req,res,next) {
  let page = parseInt(req.param("page"));
  let pageSize = parseInt(req.param("pageSize"));
  let skip = (page-1)*pageSize;

  let priceLevel = req.param("priceLevel");

  let priceGt = '',priceLte = '';

  let params = {}
  if(priceLevel != "all"){
    switch(priceLevel){
      case '0': priceGt=0;priceLte=100;break;
      case '1': priceGt=100;priceLte=500;break;
      case '2': priceGt=500;priceLte=1000;break;
      case '3': priceGt=1000;priceLte=5000;break;
    }
    params = {
      salePrice:{
        $gt:priceGt,
        $lte:priceLte
      }
    }
  }

  let sort = req.param("sort");

  let goodsModel = Goods.find(params).skip(skip).limit(pageSize);
  goodsModel.sort({'salePrice':sort});

  goodsModel.exec(function (err,doc) {
    if(err){
      res.json({
        status:1,
        msg:err.message
      });
    }else{
      res.json({
        status:0,
        msg:'',
        result:{
          count:doc.length,
          result:doc
        }
      });
    }
  });
});


module.exports = router;
